import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xim/business/model/user.dart';
import 'package:xim/screen/message_list_screen/page/chat_detail_page.dart';
import 'package:xim/screen/message_list_screen/widget/icon_action_bottom.dart';
import 'package:xim/common/style/colors.dart';
import 'package:xim/common/util/collection.dart';
import 'package:xim/common/util/datetime.dart';

/// 消息列表页面
class ChatListScreen extends StatefulWidget {
  const ChatListScreen({Key? key}) : super(key: key);

  @override
  State<ChatListScreen> createState() => _ChatListScreenState();
}

class _ChatListScreenState extends State<ChatListScreen> {

  String avatar = "https://upload.jianshu.io/users/upload_avatars/9547801/bb70e361-d8be-4f50-a4bc-1a1079c1d2f1.jpg";
  late var user = User(id: "", name: "name", avatar: avatar);
  /// appBar 的背景颜色
  Color appBarBgColor = const Color(0xffededed);
  /// AppBar 高度
  double appBarHeight = 52.0;
  /// 消息列表的高度
  double messageItemHeight = 62;
  /// 消息列表间分割线的高度
  double messageDividerHeight = 1 ;
  /// 消息列表的padding
  EdgeInsets messageEdgeInsets = const EdgeInsets.symmetric(vertical:6 , horizontal: 8);
  /// appBar
  PreferredSize get appBar => PreferredSize(
      preferredSize: Size.fromHeight(appBarHeight),
      child: AppBar(
        backgroundColor: appBarBgColor,
        title: const Text("Xim", style: TextStyle(color: StyleColor.black),),
        centerTitle: true,
        elevation: 0.5,
        actions: appBarActions(),
      ),
    );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      body: SingleChildScrollView(
        child: messageList(),
      ),
    );
  }

  /// 消息列表
  Widget messageList({bool showDivider=true}){
    return Column(
        children: List<Widget>.generate(20, (index) {
          return InkWell(
            child: messageRowItem(user, "message", DateTime.now(), edgeInsets: messageEdgeInsets),
            onTap: () {
              Get.to(const ChatDetailPage());
            },
          );
        }).splitJoin(Divider(height: messageDividerHeight,),condition: showDivider)
    );
  }

  Widget messageRowItem(User user, String message, DateTime time, {double avatarGap=12, Color? bgColor, EdgeInsets? edgeInsets}) {
    return GestureDetector(
      onLongPress: (){},
      child: Container(
        constraints: BoxConstraints(maxHeight: messageItemHeight),
        padding: edgeInsets,
        decoration: BoxDecoration(
          color: bgColor
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 用户头像
            ClipRRect(
                borderRadius: const BorderRadius.all(Radius.circular(8)),
                child: Image.network(user.avatar, width: 50,)
            ),
            SizedBox( width: avatarGap, ),
            // 用户消息
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text( user.name,style: const TextStyle(fontSize: 16,),),
                      Text(_formatDate(time),style: const TextStyle(fontSize: 12, color: Colors.grey),),
                    ],
                  ),
                  Text( message,style: const TextStyle(fontSize: 12, color: Colors.grey),)
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  List<Widget> appBarActions() {
    return [
      IconButton(
          onPressed: () {},
          icon: const Icon(
            Icons.search,
            color: StyleColor.black,
          )),
      PopupMenuButton(
        offset: const Offset(0, 60),
        icon: const Icon(
          Icons.add_circle_outline,
          color: StyleColor.black,
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        itemBuilder: (BuildContext context) {
          return [
            PopupMenuItem(
              child: IconActionBottom(
                onPressed: () {},
                icon: const Icon(
                  Icons.chat_outlined,
                  color: Colors.black,
                ),
                label: const Text(
                  "发起群聊",
                ),
              ),
            ),
            PopupMenuItem(
              child: IconActionBottom(
                onPressed: () {},
                icon: const Icon(
                  Icons.person_add_alt_outlined,
                  color: Colors.black,
                ),
                label: const Text("添加朋友"),
              ),
            ),
            PopupMenuItem(
              child: IconActionBottom(
                onPressed: () {},
                icon: const Icon(
                  Icons.document_scanner_outlined,
                  color: Colors.black,
                ),
                label: const Text("扫一扫"),
              ),
            ),
          ];
        },
      ),
    ];
  }
}



String _formatDate(DateTime dateTime){
  var nowDateTime = DateTime.now();
  var days = nowDateTime.day - dateTime.day;
  var month = nowDateTime.month - dateTime.month;
  var year = nowDateTime.year - dateTime.year;

  if (year > 0){
    // 跨年
    return dateTime.format("yyyy年M月d日");
  }
  if (month > 0){
    // 跨月
    return dateTime.format("M月d日");
  }
  if (days > 0){
    // 跨天
    return dateTime.format("M月d日");
  }
  return dateTime.format("HH:mm");
}

